package ru.ibragimoff.repository.resolver;

import ru.ibragimoff.repository.Repository;
import ru.ibragimoff.repository.resolver.exception.RepositoryNotFoundException;

import java.util.HashMap;
import java.util.Map;

public class RepositoryResolver {
    private final Map<Class<?>, Repository<?>> repositoryMap = new HashMap<>();

    public <T> void addRepository(Repository<T> repository) {
        repositoryMap.put(repository.getEntityClass(), repository);
    }

    @SuppressWarnings("unchecked")
    public <T> Repository<T> getRepository(Class<T> entityClass) throws RepositoryNotFoundException {
        if (!repositoryMap.containsKey(entityClass)) {
            throw new RepositoryNotFoundException(
                    String.format("Repository for entity %s not found", entityClass.getName())
            );
        }

        return (Repository<T>) repositoryMap.get(entityClass);
    }
}
